import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/home'
import Question from '../views/question'
import Video from '../views/video'
import User from '../views/user'
import Login from '../views/login'
import Article from '../views/article'
import appTabbar from '@/components/app-tabbar.vue'
import profile from '@/views/user/profile'
import chat from '@/views/user/chat'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    components: {
      default: Home,
      tabbar: appTabbar
    }
  },
  {
    path: '/question',
    name: 'Question',
    components: {
      default: Question,
      tabbar: appTabbar
    }
  },
  {
    path: '/video',
    name: 'Video',
    components: {
      default: Video,
      tabbar: appTabbar
    }
  },
  {
    path: '/user',
    name: 'User',
    components: {
      default: User,
      tabbar: appTabbar
    }
  },
  {
    path: '/user/profile',
    component: profile
  },
  {
    path: '/user/chat',
    component: chat
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/article',
    name: 'Article',
    component: Article
  },
  {
    path: '*',
    redirect: '/home'
  }

]

const router = new VueRouter({
  routes
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

// 路由前置守卫
// 加入黑明单
const blackList = ['User']

router.beforeEach((to, from, next) => {
  store.commit('user/clearCancelToken')
  if (blackList.includes(to.name) && !store.state.user.token) next('/login?returnUrl=' + to.fullPath)
  else next()
})

export default router
